import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:ai_data_capture/bean/response_data.dart';
import 'package:ai_data_capture/req/exp.dart';
import 'package:ai_data_capture/util/catch_util.dart';
import 'package:dio/dio.dart' as dio;
import 'package:get/get.dart';

class NetworkService extends GetxService {
  static final dio.Dio _dio = dio.Dio();
  // static var BASE_URL = "http://192.168.101.63:9090";
  static var BASE_URL = "http://10.255.76.63:9090";
  // static var BASE_URL = "http://10.28.1.140:9090";
  // static var BASE_URL = "http://127.0.0.1:9090";
  static Future<ResponseData?> post(
      {required String url, required Map<String, dynamic> map}) async {
    try {
      log("emmmmm_url:$BASE_URL/$url");
      var header = {"Authorization": "Token ${await CacheUtil.getToken()}"};
      print(header);
      var res = (await _dio.post("$BASE_URL/$url",
          options:
              dio.Options(headers: header, contentType: 'application/json'),
          data: map));
      log("请求数据($url):${json.encode(res.data)}");
      var data = ResponseData.fromJson(res.data);
      if (data.code == "200") {
        return data;
      } else {
        // if (data.code == "401") {
        //   showToast("用户信息失效，请重新登录");
        //   await CacheUtil.saveToken('');
        //   Get.offAllNamed(RoutePath.login);
        //   throw ApiException(code: "401", message: '${data.message}');
        // } else {
        //   throw ApiException(
        //       code: EXP.apiError.code, message: '${data.message}');
        // }

        throw ApiException(code: EXP.apiError.code, message: '${data.message}');
      }
    } on dio.DioException catch (e) {
      // if ("${e.response?.statusCode}" == "401") {
      //   showToast("用户信息失效，请重新登录");
      //   await CacheUtil.saveToken('');
      //   Get.offAllNamed(RoutePath.login);
      //   throw ApiException(code: EXP.userExpired.code, message: '用户信息失效');
      // } else {
      //   throw ApiException(code: EXP.httpError.code, message: '$e');
      // }
      throw ApiException(code: EXP.httpError.code, message: '$e');
    } catch (e) {
      rethrow;
    }
  }
}
